package es.udc.empresauriostic.geofinder.view;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import es.udc.empresauriostic.geofinder.R;
import es.udc.empresauriostic.geofinder.model.ServerAPI;
import es.udc.empresauriostic.geofinder.model.utils.Util;
import es.udc.empresauriostic.geofinder.view.utils.ViewUtils;

public class LoginActivity extends Activity {
	private SharedPreferences preferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		preferences = getSharedPreferences(
				getString(R.string.const_string_preferences),
				Activity.MODE_PRIVATE);
		setContentView(R.layout.login_layout);
		if (preferences.getBoolean("logged_in", false)) {
			if (preferences.getLong("current_game_id", -1) != -1) {
				startActivity(new Intent(getApplicationContext(),
						GameActivity.class));
			} else {
				startActivity(new Intent(getApplicationContext(),
						GamesOverviewActivity.class));
			}
		}
		configViews();
	}

	private void configViews() {
		((Button) findViewById(R.id.button_login))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						String email = ((EditText) findViewById(R.id.email_input))
								.getText().toString();
						String password = ((EditText) findViewById(R.id.password_input))
								.getText().toString();
						password = Util.hashPassword(password);

						Editor editor = preferences.edit();
						editor.putString("email", email);
						editor.putString("user_password", password);
						editor.commit();
						new AsyncLogin().execute();
					}
				});
		((Button) findViewById(R.id.button_register))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						showRegisterDialog();
					}
				});
	}

	private class AsyncLogin extends AsyncTask<Void, Void, Pair<Long, Long>> {
		private boolean connectionProblem = false;

		@Override
		protected Pair<Long, Long> doInBackground(Void... params) {
			try {
				return ServerAPI.login(getApplicationContext());
			} catch (IOException e) {
				connectionProblem = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Pair<Long, Long> result) {
			super.onPostExecute(result);
			if (result != null) {
				Editor editor = preferences.edit();
				editor.putBoolean("logged_in", true);
				editor.putLong("user_id", result.first);
				editor.commit();
				if (result.second != -1) {
					startActivity(new Intent(getApplicationContext(),
							GameActivity.class));
				} else {
					if (result.first != -1) {
						startActivity(new Intent(getApplicationContext(),
								GamesOverviewActivity.class));
					}
				}
			} else {
				if (connectionProblem) {
					ViewUtils
							.showToastConnectionProblem(getApplicationContext());
				} else {
					ViewUtils.showToast(getApplicationContext(),
							R.string.wrong_credentials);
				}
			}
		}
	}

	private class AsyncRegister extends AsyncTask<String, Void, Long> {
		private boolean connectionProblem = false;
		private String[] data;

		@Override
		protected Long doInBackground(String... params) {
			data = params;
			try {
				return ServerAPI.register(getApplicationContext(), params[0],
						params[1], params[2]);
			} catch (IOException e) {
				connectionProblem = true;
			}
			return Long.valueOf(-1);
		}

		@Override
		protected void onPostExecute(Long result) {
			super.onPostExecute(result);
			if (result != -1) {
				Editor editor = preferences.edit();
				editor.putBoolean("logged_in", true);
				editor.putString("email", data[0]);
				editor.putString("username", data[1]);
				editor.putString("password", data[2]);
				editor.putLong("user_id", result);
				editor.commit();
				startActivity(new Intent(getApplicationContext(),
						GamesOverviewActivity.class));
			} else {
				if (connectionProblem) {
					ViewUtils
							.showToastConnectionProblem(getApplicationContext());
				} else {
					ViewUtils.showToast(getApplicationContext(),
							R.string.pick_another_username);
				}
			}
		}
	}

	private Dialog showRegisterDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				LoginActivity.this);
		LayoutInflater inflater = getLayoutInflater();
		final View view = inflater.inflate(R.layout.registration_dialog, null);
		builder.setView(view)
				.setPositiveButton(R.string.confirm_register,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								String email = ((EditText) view
										.findViewById(R.id.register_email_input))
										.getText().toString();

								String username = ((EditText) view
										.findViewById(R.id.register_username_input))
										.getText().toString();
								String password = Util.hashPassword(((EditText) view
										.findViewById(R.id.register_password_input))
										.getText().toString());
								Editor editor = preferences.edit();
								editor.putString("email", email);
								editor.putString("user_password", password);
								editor.putString("username", username);
								editor.commit();
								// FIXME
								new AsyncRegister().execute(email, username,
										password);
							}
						}).setTitle(R.string.register_dialog_title);
		return builder.show();
	}

	// TODO show waiting dialogs
	// TODO override back button

}
